# Based on procedure described in Mordin on Time. Speed rating equates one 
# length (or fifth of second) to one point per mile.

# Deduct standard time for course and distance from winner's adjusted time, and 
# divide result by distance of race as fraction of 1 mile to find how much 
# slower or faster winning time was per mile
runners <- merge(runners, races[, c("race_id",
                                    "meeting_date",
                                    "course",
                                    "distance_yards",
                                    "winning_time_adjstd",
                                    "stdtime")],
                 by = "race_id")
runners <- transform(runners, delta_per_mile =
  ifelse(finish_position == 1,
         (winning_time_adjstd - stdtime) / distance_yards * 1760, NA)
)

# To calculate going allowance for meeting date and course, calculate median of
# how much slower or faster winning times were per mile
goings <- aggregate(delta_per_mile ~ meeting_date + course, runners,
                    FUN = median, na.rm = T)

names(goings)[names(goings) == "delta_per_mile"] <- "going"
runners <- merge(runners, goings, by = c("meeting_date", "course"))
rm(goings)

# To arrive at speed rating for winner, deduct going allowance from how much 
# slower or faster winning time was per mile, multiply by five, and subtract 
# from hundred
runners <- transform(runners, winner_rating =
  round(100 - 5 * (delta_per_mile - going))
)

# After allocating speed rating for winner, divide number of lengths each horse 
# trailed winner by race distance as fraction of 1 mile, and deduct from 
# winner's speed rating
winner.ratings <- subset(runners, !is.na(winner_rating),
                         c("race_id", "winner_rating"))
runners <- merge(runners, winner.ratings[!duplicated(winner.ratings),],
                 by = c("race_id")) # workaround for ties
rm(winner.ratings)
runners <- transform(runners, speed_rating =
  ifelse(finish_position == 1,
         winner_rating.x,
         round(winner_rating.y - distance_behind_winner / distance_yards * 1760)
  )
)
runners <- subset(runners, T,
                  -c(delta_per_mile, going, winner_rating.x, winner_rating.y))